package cqrtplm.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dingtalkrobot_1_0.Client;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOHeaders;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTORequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.taobao.api.ApiException;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.response.ResponseResult;
import cqrtplm.constant.RouteConstant;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping(RouteConstant.NOTIFY+"v1")
@Api(tags = "系统发送通知给钉钉")
public class SendMesDingDingController {
    @Value("${dingtalk.robot-code:dingl79wtn5gxpazxz9d}")
    private String robotCode;
    @Value("${dingtalk.plm-url:http://192.168.102.91:7002}")
    private String plmBaseUrl;
    @Value("${dingtalk.key:dingl79wtn5gxpazxz9d}")
    private String appKey;
    @Value("${dingtalk.secret:xmRdvGIMcQu2vKeOmACgvs9yp5nLJjdQrLIfuIbdCCnhCGO-8Z8bIo8AQFGZZd6-}")
    private String appSecret;


        @PostMapping("/sendMesDingDing")
        public ResponseResult snedMesDingDing()throws Exception{
            // 获取token
            String accessToken = getAccessToken();

            // 获取用户ID、
            UserDO user = CommonUtil.getUser();
            String userId = getUserId(user.getOid().toString(), accessToken);

            // 获取当前时间
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            // 构造消息内容
            String title = "**PLM-流程审批通知**" + currentTime;
            String text  = "**PLM-流程审批通知**" + currentTime + "【】您好：您有一个流程需审批,[去审批](plmBaseUrl+)";

            // 发送消息
            sendMsgByRobot(
                    robotCode,
                    accessToken,
                    Collections.singletonList(userId),
                    title,
                    text
            );
            return ResponseResult.success();
        }

    public static void sendMsgByRobot(String robotCode, String accessToken, List<String> userIds, String title, String text) throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        Client client = new Client(config);

        BatchSendOTOHeaders batchSendOTOHeaders = new BatchSendOTOHeaders();
        batchSendOTOHeaders.xAcsDingtalkAccessToken = accessToken;
        BatchSendOTORequest batchSendOTORequest = new BatchSendOTORequest()
                .setRobotCode(robotCode)
                .setUserIds(userIds)
                .setMsgKey("sampleMarkdown")
                .setMsgParam(String.format("{\"text\": \"%s\",\"title\": \"%s\"}", text, title));
        try {
            client.batchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, new RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
        }
    }

    public static String getUserId(String mobile, String accessToken) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(mobile);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);
            System.out.println(rsp.getBody());
            JSONObject result = (JSONObject) JSON.parseObject(rsp.getBody()).get("result");
            System.out.println((String) result.get("userid"));
            return (String) result.get("userid");
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getAccessToken() throws IOException {
        String appKey = "dingl79wtn5gxpazxz9d";
        String appSecret = "xmRdvGIMcQu2vKeOmACgvs9yp5nLJjdQrLIfuIbdCCnhCGO-8Z8bIo8AQFGZZd6-";
        String requestUrl = "https://oapi.dingtalk.com/gettoken?appkey=" + appKey + "&appsecret=" + appSecret;

        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println(response.toString());
            JSONObject jsonObject=JSONObject.parseObject(response.toString());

            return jsonObject.getString("access_token");
        } else {
            System.out.println("GET请求失败，状态码：" + responseCode);
        }

        return "";
    }
}
